<template>
  <div class="container">
    <el-form
      class="eltabBox"
      :model="formDataChange"
      :rules="rulesChange"
      ref="ruleFormChange"
    >
      <div class="title">
        项目状态变更审核配置
        <el-button
          :loading="saveConfigLoading"
          class="commonBut saveBtn funComBut fr"
          @click="handleAddChange('ruleFormChange')"
          style="margin-left: 124px"
        >
          保存
        </el-button>
      </div>
      <div style="margin-bottom: 38px">
        <el-form-item
          label="项目状态变更审核："
          class="row-padding-bottom insurance"
        >
          <el-radio-group
            v-model="formDataChange.status"
            @change="changeProValue"
          >
            <el-radio :label="1">开启审核</el-radio>
            <el-radio :label="0">关闭审核</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="auditBox" v-if="showAuditPer">
          <div class="secondaryTitle secondaryTitleTheme">审核条件</div>
          <div style="padding-left: 14px">
            <!-- <p class = "color333 fontSizeF fontWeight mrT24 mrB18">1. 开启审核后，以下状态的项目变更状态时，需要审核</p> -->
            <el-form-item
              label="1. 开启审核后，以下状态的项目变更状态时，需要审核"
              class="row-padding-bottom checkSty"
              prop="checkList"
            >
              <div style="padding-left: 16px">
                <el-checkbox-group v-model="formDataChange.checkList">
                  <el-checkbox
                    v-for="item in statusOptions"
                    :key="item.id"
                    :label="item.id"
                    >{{ item.name }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </el-form-item>

            <p
              class="color333 fontSizeF fontWeight mrB18"
              style="padding-left: 10px"
            >
              2. 开启审核后，满足以下考勤条件时，需要审核
            </p>
            <div
              style="
                width: 700px;
                vertical-align: top;
                display: inline-block;
                padding-left: 16px;
              "
            >
              <span class="color333 fontSizeF">近</span>
              <el-select
                v-model="formDataChange.attMonth"
                clearable
                placeholder="请选择"
                style="width: 135px"
              >
                <el-option
                  v-for="(item, index) of monthArr"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <span class="color333 fontSizeF">个月有考勤（含当前月）</span>
            </div>
          </div>
          <div class="secondaryTitle secondaryTitleTheme mrT40 mrB12">
            审核人账号
          </div>
          <el-form-item
            label="审核人账号："
            class="row-padding-bottom insurance"
            prop="auditPer"
            label-width="100px"
            style="padding-left: 14px"
          >
            <div class="accountBox">
              <span v-for="(item, index) of list" :key="index"
                >{{ item.nickname }}（{{ item.username }}）<span
                  v-show="index != list.length - 1"
                  >、</span
                ></span
              >
              <el-link icon="el-icon-edit" class="icon" @click="toEdit"
                >编辑</el-link
              >
            </div>
          </el-form-item>
        </div>
        <el-form-item
          label="状态变更必填字段："
          class="row-padding-bottom insurance mrT mrB12"
        >
          <el-checkbox
            v-model="formDataChange.isReason"
            @change="getCheckedReason"
            >变更原因说明</el-checkbox
          >
          <el-checkbox v-model="formDataChange.isFile" @change="getCheckedFile"
            >上传变更附件</el-checkbox
          >
        </el-form-item>
        <el-form-item
          label="状态变更权限用户："
          class="row-padding-bottom insurance"
        >
          <el-checkbox
            :true-label="'1'"
            :false-label="'0'"
            v-model="formAdmin.gtJC"
            disabled
            >劳动监察</el-checkbox
          >
          <el-checkbox
            :true-label="'1'"
            :false-label="'0'"
            v-model="formAdmin.gtHY"
            >行业主管</el-checkbox
          >
          <el-checkbox
            :true-label="'1'"
            :false-label="'0'"
            v-model="formAdmin.gtQY"
            >企业用户</el-checkbox
          >
          <el-checkbox
            :true-label="'1'"
            :false-label="'0'"
            v-model="formAdmin.gtXM"
            >项目管理员</el-checkbox
          >
        </el-form-item>
      </div>
    </el-form>
    <el-dialog
      :close-on-click-modal="false"
      title="设置审核人"
      :visible.sync="formVisible"
      width="550px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form :inline="true" :model="ruleForm" :rules="rules" ref="ruleForm">
        <div class="tipSty" v-if="isShowTip">请至少设置一人</div>
        <el-form-item label="劳动监察" prop="jcUsers">
          <el-select
            class="form-item"
            v-model="ruleForm.jcUsers"
            filterable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in jcUsersOptions"
              :key="item.id"
              :label="item.nickname + '(' + item.username + ')'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行业主管" prop="hyUsers">
          <el-select
            v-model="ruleForm.hyUsers"
            class="form-item"
            filterable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in hyUsersOptions"
              :key="item.id"
              :label="item.nickname + '(' + item.username + ')'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()" class="cancel">取 消</el-button>
        <el-button type="primary" @click="save('ruleForm')" class="save"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'changeAuditConfig',
  data() {
    var validateJcUsers = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error('最多可选 10 个'))
      } else {
        callback()
      }
    }
    var validateHyUsers = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error('最多可选 10 个'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      ruleForm: {
        jcUsers: '',
        hyUsers: '',
      },
      jcUsersOptions: [],
      hyUsersOptions: [],
      rules: {
        jcUsers: [{ validator: validateJcUsers, trigger: 'change' }],
        hyUsers: [{ validator: validateHyUsers, trigger: 'change' }],
      },
      formVisible: false,
      showAuditPer: true,
      isShowTip: false,
      jcSelectUsers: [],
      hySelectUsers: [],
      formDataChange: {
        status: 0,
        isReason: true,
        isFile: true,
        attMonth: '',
        checkList: [],
      },
      id: '',
      rulesChange: {
        checkList: [
          {
            required: true,
            message: '请选择项目状态',
            trigger: 'change',
          },
        ],
      },
      statusOptions: [],
      formAdmin: {
        gtJC: '',
        gtHY: '',
        gtQY: '',
        gtXM: '',
      },
      monthArr: [1, 2, 3, 4, 5, 6],
    }
  },
  watch: {
    'ruleForm.jcUsers'(newVal) {
      if (newVal) {
        this.isShowTip = false
      }
    },
    'ruleForm.hyUsers'(newVal) {
      if (newVal) {
        this.isShowTip = false
      }
    },
  },
  created() {
    this.getAuditConfig()
    this.getCheckUsers('MONITOR')
    this.getCheckUsers('DIRECTOR')
    this.getStatus()
    this.getOauthConfig()
  },
  methods: {
    // 获取配置
    getAuditConfig() {
      this.axios({
        method: 'post',
        url: 'api-p/cs/projectstatusauditconfig/getConfig',
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              var result = res.data.result
              this.formDataChange.status =
                result.status == null || result.status == '' ? 0 : result.status
              this.formDataChange.isReason = result.isReason == 1 ? true : false
              this.formDataChange.isFile = result.isFile == 1 ? true : false
              this.id = result.id
              if (result.status == 1) {
                this.showAuditPer = true
              } else {
                this.showAuditPer = false
              }
              if (
                result.industryAuditList == null ||
                result.industryAuditList == ''
              ) {
                result.industryAuditList = []
              }
              if (
                result.monitorAuditList == null ||
                result.monitorAuditList == ''
              ) {
                result.monitorAuditList = []
              }
              this.list = result.industryAuditList.concat(
                result.monitorAuditList
              )
              this.jcSelectUsers = []
              this.hySelectUsers = []
              result.monitorAuditList.forEach((each, i) => {
                this.jcSelectUsers.push(each.id)
              })
              result.industryAuditList.forEach((each, i) => {
                this.hySelectUsers.push(each.id)
              })
              this.formDataChange.checkList =
                result.projectStatusCon.length > 0
                  ? result.projectStatusCon.split('-')
                  : []
              this.formDataChange.attMonth = result.attMonthCount
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    getCheckUsers(type) {
      this.axios({
        method: 'post',
        url: 'api-p/cs/projectstatusauditconfig/getAuditor',
        data: {
          type: type,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError && res.data.result) {
              if (type == 'MONITOR') {
                this.jcUsersOptions = res.data.result
              } else {
                this.hyUsersOptions = res.data.result
              }
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    // 编辑
    toEdit() {
      this.ruleForm.jcUsers = this.jcSelectUsers
      this.ruleForm.hyUsers = this.hySelectUsers
      this.formVisible = true
    },
    cancel() {
      this.formVisible = false
    },
    // 保存审核人
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.jcUsers == '' && this.ruleForm.hyUsers == '') {
            this.isShowTip = true
            return
          }
          this.list = []
          this.ruleForm.jcUsers.forEach((item, index) => {
            this.jcUsersOptions.forEach((each, i) => {
              if (item == each.id) {
                this.list.push(each)
              }
            })
          })
          this.ruleForm.hyUsers.forEach((item, index) => {
            this.hyUsersOptions.forEach((each, i) => {
              if (item == each.id) {
                this.list.push(each)
              }
            })
          })
          this.jcSelectUsers = this.ruleForm.jcUsers
          this.hySelectUsers = this.ruleForm.hyUsers
          this.formVisible = false
        } else {
          return false
        }
      })
    },
    // 开启审核显示审核人
    changeProValue(val) {
      if (val == 1) {
        this.showAuditPer = true
      } else {
        this.showAuditPer = false
      }
    },
    getCheckedReason(value) {
      this.formDataChange.isReason = value
    },
    getCheckedFile(value) {
      this.formDataChange.isFile = value
    },
    handleAddChange(formName) {
      if (this.list.length < 0) {
        this.$message({
          message: '审核人账号不能为空',
          type: 'error',
        })
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editOauthConfig()
          var arr = this.formDataChange.checkList
          this.axios({
            method: 'post',
            url: 'api-p/cs/projectstatusauditconfig/editConfig',
            data: {
              isReason: this.formDataChange.isReason == true ? 1 : 0,
              isFile: this.formDataChange.isFile == true ? 1 : 0,
              status: this.formDataChange.status,
              monitorAudit:
                this.jcSelectUsers.length > 0
                  ? this.jcSelectUsers.toString()
                  : [],
              industryAudit:
                this.hySelectUsers.length > 0
                  ? this.hySelectUsers.toString()
                  : [],
              id: this.id,
              projectStatusCon: arr.length > 0 ? arr.join('-') : [],
              attMonthCount: this.formDataChange.attMonth,
            },
          })
            .then(
              (res) => {
                if (!res.data.hasError) {
                  this.$message({
                    message: res.data.result,
                    type: 'success',
                  })
                  this.getAuditConfig()
                } else {
                  this.$message({
                    message: res.data.errorMsg,
                    type: 'error',
                  })
                }
              },
              (res) => {
                // this.$message({
                //   message: res.data.errorMsg,
                //   type: "error"
                // });
              }
            )
            .catch((error) => {})
        }
      })
    },
    getStatus() {
      this.axios({
        method: 'post',
        url: '/api-p/projectstats/expand/status',
      })
        .then((response) => {
          let arr = response.data.result
          this.statusOptions = arr
        })
        .catch((response) => {})
    },
    getOauthConfig() {
      this.axios({
        method: 'get',
        url: '/api-p/cs/projectstatusauditconfig/getOauthConfig',
      })
        .then((response) => {
          if (!response.data.hasError) {
            let str = response.data.result
            let arr = str.split(',')
            this.formAdmin = {
              gtJC: arr[0],
              gtHY: arr[1],
              gtQY: arr[2],
              gtXM: arr[3],
            }
          }
        })
        .catch((response) => {})
    },
    editOauthConfig() {
      let { gtJC, gtHY, gtQY, gtXM } = this.formAdmin
      var data = gtJC + ',' + gtHY + ',' + gtQY + ',' + gtXM
      this.axios({
        method: 'post',
        url: '/api-p/cs/projectstatusauditconfig/editOauthConfig',
        data: {
          value: data,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.getOauthConfig()
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((response) => {})
    },
  },
}
</script>

<style scoped lang="less">
.saveBtn {
  height: 36px;
  // font-family: SourceHanSansCN-Normal;
  font-size: 14px;
  color: #ffffff;
  text-align: center;
}
.eltabBox {
  padding: 24px;
}
// 标题栏样式
.title {
  margin-top: 10px;
  margin-bottom: 24px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.insurance /deep/ .el-form-item__label {
  width: 140px;
}
.insuranceSty /deep/ .el-form-item__label {
  width: 222px;
}
.insuranceSty /deep/.el-input__inner {
  width: 260px;
}
.form-item {
  width: 300px;
}
.el-form1 /deep/ .el-form-item__error {
  left: 220px !important;
}

.tipSty {
  position: absolute;
  top: 26px;
  left: 130px;
  color: red;
  font-size: 12px;
}
.auditBox {
  background: #f8f9fb;
  border: 1px solid rgba(220, 223, 230, 1);
  padding: 20px 24px;
}
.mrT {
  margin-top: 20px;
}
.mrT40 {
  margin-top: 40px;
}
.mrB12 {
  margin-bottom: 12px;
}
.checkSty {
  /deep/.el-form-item__label {
    float: none;
  }
}
</style>
